package com.eaxi.a.smsproxy;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by mikeliang on 21/10/2017.
 */

public class SmsReceiver extends BroadcastReceiver {
    final SmsManager sms = SmsManager.getDefault();
    @Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();
        try {

            if (bundle != null) {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                StringBuilder sb = new StringBuilder();
                String firstSender = null;
                long firstTime = 0;
                boolean hasOtherMessage = false;
                for (int i = 0; i < pdusObj.length; i++) {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    long time = currentMessage.getTimestampMillis();
                    String sender = currentMessage.getDisplayOriginatingAddress();
                    String body = currentMessage.getDisplayMessageBody();
                    if (firstSender == null) {
                        firstSender = sender;
                        firstTime = time;
                    }
                    if (firstSender != null && !sender.equals(firstSender)) {
                        // Bundle中出现其他消息，直接发出去
                        SmsObject singleSmsObject = new SmsObject();
                        singleSmsObject.setSender(sender);
                        singleSmsObject.setTime(time);
                        singleSmsObject.setBody(body);

                        ObservableObject.getInstance().updateValue(singleSmsObject);
                        hasOtherMessage = true;
                    } else {
                        //Log.i("TIME", "chunk " + i + "=" + body);
                        sb.append(body);
                    }

                } // end for loop
                if (!hasOtherMessage) {
                    SmsObject merged = new SmsObject();
                    merged.setTime(firstTime);
                    merged.setSender(firstSender);
                    merged.setBody(sb.toString());
                    //Log.i("MERGED", sb.toString());
                    ObservableObject.getInstance().updateValue(merged);
                }
            } // bundle is null

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);

        }
    }
}
